package com.joeyzh.base.filter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.joey.ui.general.BaseActivity;
import com.joeyzh.R;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 筛选Base类 提取公共功能（返回上一层、Save、恢复默认）
 *
 * @author Joey
 */
public abstract class FilterBaseActivity extends BaseActivity
        implements View.OnClickListener, OnFilterItemChangeCallback {
    protected RadioGroup rgCheck = null;

    /**
     * 恢复默认按钮
     */
    protected Button btnNegative;
    protected Button btnPositive;

    /**
     * 当前筛选类的类名
     */
    protected String filterClassName;
    /**
     * 筛选界面中具有的筛选按钮列表
     */
    private ArrayList<RadioButton> FilterButtonList;

    /**
     * 筛选条件数据的键值对 ：key：筛选项；value：arrayList arrayList:需调用服务器接口，拿到数据放到arrayList
     */
    protected HashMap<Integer, ArrayList<String>> datalistsHashMap = new HashMap<Integer, ArrayList<String>>();

    /**
     * 具有的筛选
     */
    protected ArrayList<Integer> FilterItemList = new ArrayList<>();

    /**
     * 在具有的筛选项上维系一个键值对，该键值对中value储存的值为筛选的值（以后可以适当优化，将List和HashMap合并，维持一个集合，而不是两个
     * ）
     */
    protected HashMap<Integer, String> FilterItemDataHashMap;
    protected int currentIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.ifr_tab_filter_fragment);

        InitView();

        SetFilterItemList();
        SetFilterItemDataHashMap();

        InitFilterButtonList();

        BindFilterItem();
        // 获取筛选条件
    }

    private void InitView() {

        btnPositive = (Button) findViewById(R.id.btn_positive);
        btnNegative = (Button) findViewById(R.id.btn_negative);

        rgCheck = (RadioGroup) findViewById(R.id.rg_check);

        btnNegative.setOnClickListener(this);
        btnPositive.setOnClickListener(this);

        filterClassName = GetClassName();

    }

    /**
     * 获取类名
     *
     * @return 类名
     */
    private String GetClassName() {
        String strFulClassName = this.getClass().getCanonicalName();
        String[] tmpArray = strFulClassName.split("\\.");
        return tmpArray[tmpArray.length - 1];
    }

    /**
     * 获取界面筛选按钮列表
     */
    private void InitFilterButtonList() {
        FilterButtonList = new ArrayList<>();
        for (int i = 0; i < FilterItemList.size(); i++) {
            RadioButton radioButton = (RadioButton) View.inflate(this, R.layout.include_filter_property_item, null);
            radioButton.setText(FilterItemList.get(i));
            radioButton.setOnClickListener(rbItem_ClickListener);
            radioButton.setTag(FilterItemList.get(i));
            int height = getResources().getDimensionPixelOffset(R.dimen.filter_radio_height);
            rgCheck.addView(radioButton, new RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height));
            FilterButtonList.add(radioButton);
        }
        if (currentIndex >= 0 && currentIndex < FilterButtonList.size()) {
            FilterButtonList.get(currentIndex).setChecked(true);
            gotoFilterItem_Fragment(FilterItemList.get(currentIndex));
        }

    }

    /**
     * 绑定项
     */
    protected void BindFilterItem() {
        for (int i = 0; i < FilterButtonList.size(); i++) {

            if (i < FilterItemList.size()) {
                String value = getResources().getString(FilterItemList.get(i));
                if (FilterItemDataHashMap.get(FilterItemList.get(i)).isEmpty()) {
                    FilterButtonList.get(i).setText(value);
                } else {
                    /**
                     * 设置指定位置文字的颜色
                     */
                    SpannableStringBuilder styleText = new SpannableStringBuilder("●" + value);
                    int accentColor = getResources().getColor(R.color.colorAccent);
                    ForegroundColorSpan colorSpan = new ForegroundColorSpan(accentColor);
                    styleText.setSpan(colorSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    FilterButtonList.get(i).setText(styleText);
                }

                FilterButtonList.get(i).setTag(FilterItemList.get(i));
                FilterButtonList.get(i).setVisibility(View.VISIBLE);

            } else {
                FilterButtonList.get(i).setVisibility(View.GONE);

            }
        }

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_positive) {
            save();
            return;
        }
        if (v.getId() == R.id.btn_negative) {
            cleanAll();
            return;
        }
    }

    /**
     * 筛选项 项点击事件
     */
    View.OnClickListener rbItem_ClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            int iTag = (Integer) arg0.getTag();
            gotoFilterItem_Fragment(iTag);
        }
    };

    /**
     * 初次进入界面调用该方法前，必须先调用SetFilterItemList，否则拿不到之前保存的筛选数据
     * 从SharedPreferences中拿到之前保存的数据
     */
    protected void SetFilterItemDataHashMap() {
        FilterItemDataHashMap = new HashMap<Integer, String>();
        SharedPreferences preferences = getSharedPreferences(filterClassName, Activity.MODE_PRIVATE);
        if (preferences == null) {
            return;
        }
        for (int i = 0; i < FilterItemList.size(); i++) {
            // 从SharedPreferences中取值
            String strFilterItemName = getResources().getString(FilterItemList.get(i));
            String strValue = preferences.getString(strFilterItemName, "");

            // strValue = SetDefaultValue(FilterItemList.get(i), strValue);
            // 加入到HashMap
            // 此处写默认代码
            FilterItemDataHashMap.put(FilterItemList.get(i), strValue);
        }
    }

    @Override
    public void RefreshDataOrMenuItem(int Key, String Value) {
        if (Value.equals("不限")) {
            Value = "";
        }
        FilterItemDataHashMap.put(Key, Value);
        BindFilterItem();
    }

    protected void cleanAll() {
        SharedPreferences sharedPreferences = getSharedPreferences(filterClassName, Context.MODE_PRIVATE);
        Editor editor = sharedPreferences.edit();

        editor.clear();
        editor.commit();

        SetFilterItemDataHashMap();

        SetDefaultValue();

        BindFilterItem();

        // 得到当前筛选项、重新跳转到这个界面，达到恢复默认后刷新界面的效果
        int iTag = Integer.parseInt(findViewById(rgCheck.getCheckedRadioButtonId()).getTag().toString());
        gotoFilterItem_Fragment(iTag);
    }


    /**
     * 保存方法
     */
    public void save() {
        if (!checkFilterInfo()) {
            return;
        }
        SharedPreferences sharedPreferences = getSharedPreferences(filterClassName, Context.MODE_PRIVATE);
        Editor editor = sharedPreferences.edit();
        String value;
        String KeyValue;
        for (int i = 0; i < FilterItemList.size(); i++) {
            // 拿到集合中当前值
            value = FilterItemDataHashMap.get(FilterItemList.get(i));

            // 拿到Key值
            KeyValue = getResources().getString(FilterItemList.get(i));
            // 添加到SharedPerences
            editor.putString(KeyValue, value);
        }

        // 提交
        editor.commit();

        setResult(RESULT_OK, new Intent());
        // 关闭界面
        finish();
//        // 页面跳转动画
//        overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
    }

    /**
     * 设置筛选项的默认值
     */
    protected abstract void SetDefaultValue();

    /**
     * 检查筛选条件，如果有必填项，请在这里判断一下必填项是否存在了
     *
     * @return
     */
    protected boolean checkFilterInfo() {
        return true;
    }

    /**
     * 子类必须实现设置筛选项
     */
    protected abstract void SetFilterItemList();

    /**
     * 根据key（点击的是哪一个filter），跳转到子界面
     *
     * @param currentKey
     */
    protected abstract void gotoFilterItem_Fragment(int currentKey);


}
